<?php

use Illuminate\Database\Capsule\Manager as DB;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;

#[店铺角色管理]
class Dianpu_RolesController extends AcommonController
{

    public function init()
    {
        $this->model      = (new \app\modules\Admin\models\merchantrolesModel());
        $this->table      = 'merchant_roles';
        $this->primaryKey = 'id';
        parent::init();
    }

    #[店铺角色列表]
    public function indexAction($returnData = FALSE)
    {
        if($this->isPost()){
            $page     = $this->get('page', 1);
            $limit    = $this->get('rows', 10);
            $offset   = ($page - 1) * $limit;
            $sort     = $this->get('sort', 'id');
            $order    = $this->get('order', 'asc');
            $keywords = trim($this->get('keywords', ''));
            $query    = $this->model;
            if ($keywords !== '') {
                $query = $query->where('rolename', 'like', "%{$keywords}%");
            }
            $total = $query->count();
            $rows  = $query->orderBy($sort, $order)
                           ->offset($offset)
                           ->limit($limit)
                           ->get();

            json(['total' => $total, 'rows' => $rows]);
        }else{
            $this->_view->display('dianpu_roles/index.html');
        }
    }

    #[增加店铺角色]
    public function addAction()
    {
        if (!$this->isPost()) {
            $rows = \app\modules\Admin\models\merchantmenusModel::query()->where('up', '=', 0)->orderBy('sortorder', 'desc')->select('id', 'name as text')->get();
            if ($rows->isNotEmpty()) {
                \app\modules\Admin\service\Dianpumenus::getAllChildren($rows, 'up', 'text');
            }
            $this->_view->assign('menus', $rows);
            $this->_view->display('dianpu_roles/add.html');
        } else {
            do {
                $rolename  = $this->get('name', '');
                $menu_ids  = $this->get('menu_ids');
                $render_ids  = $this->get('render_ids');
                $sortorder = $this->get('sortorder', 500);
                if (empty($rolename) || empty($menu_ids)) {
                    $result = [
                        'code' => '300',
                        'msg'  => '角色名或权限列表不能为空',
                    ];
                    break;
                }
                $rows = [
                    'name'       => $rolename,
                    'menu_ids'   => $menu_ids,
                    'render_ids' => $render_ids,
                    'sortorder'  => $sortorder,
                    'created_at' => date("Y-m-d H:i:s"),
                ];
                if ($this->model->insert($rows)) {
                    $result = [
                        'ret' => 0,
                        'msg'  => '操作成功',
                    ];
                } else {
                    $result = [
                        'ret' => 300,
                        'msg'  => '添加角色失败,请多试几下',
                    ];
                }
            } while (FALSE);
            json($result);
        }
    }

    #[编辑店铺角色]
    public function editAction()
    {
        if (!$this->isPost()) {
            $id = $this->get('id', NULL);
            if ($id == NULL) return FALSE;
            $dataset = $this->model->find(intval($id));
            $menus   = explode(',', $dataset->render_ids);
            $rows = \app\modules\Admin\models\merchantmenusModel::query()->where('up', '=', 0)->orderBy('sortorder', 'desc')->select('id', 'name as text')->get();
            if ($rows->isNotEmpty()) {
                \app\modules\Admin\service\Dianpumenus::getAllChildren($rows, 'up', 'text', $menus);
            }
            $this->_view->assign('menus', $rows);
            $this->_view->assign('dataset', $dataset);
            $this->_view->display('dianpu_roles/edit.html');
        } else {
            do {
                $id        = $this->get('id', '');
                $name      = $this->get('name', '');
                $menu_ids  = $this->get('menu_ids', '');
                $render_ids  = $this->get('render_ids', '');
                $sortorder = $this->get('sortorder', 500);
                if (empty($name) || empty($menu_ids)) {
                    $result = [
                        'code' => '300',
                        'msg'  => '角色名或菜单列表不能为空',
                    ];
                    break;
                }
                $rows = [
                    'name'       => $name,
                    'menu_ids'   => $menu_ids,
                    'render_ids' => $render_ids,
                    'sortorder'  => $sortorder,
                    'updated_at' => date("Y-m-d H:i:s"),
                ];
                if ($this->model->where('id', '=', $id)->update($rows)) {
                    $merchant_manager = \app\modules\Admin\models\merchantModel::query()->where('roles_id', $id)->pluck('id')->toArray();
                    if(!empty($merchant_manager)){
                        foreach ($merchant_manager as $m_id){
                            forget('merchant_auths_' . $m_id);
                        }
                    }
                    unset($merchant_manager, $m_id);
                    $result = [
                        'ret' => 0,
                        'msg' => '操作成功',
                    ];
                } else {
                    $result = [
                        'ret' => 3,
                        'msg' => '添加角色失败,请多试几下',
                    ];
                }
            } while (FALSE);
            json($result);
        }
    }

    #[删除店铺角色]
    public function deleteAction()
    {
        do {
            $id = $this->get('id');
            if (empty($id)) {
                $result = [
                    'ret'  => 300,
                    'msg'  => '参数为空',
                ];
                break;
            }
            if($this->model->where('id', $id)->doesntExist()){
                $result = [
                    'ret'  => 300,
                    'msg'  => '角色不存在',
                ];
                break;
            }
            if (\app\modules\Admin\models\merchantModel::query()->where('roles_id', $id)->exists()){
                $result = [
                    'ret'  => 300,
                    'msg'  => '角色被使用，无法删除',
                ];
                break;
            }
            if ($this->model->delete($id)) {
                $merchant_manager = \app\modules\Admin\models\merchantModel::query()->where('roles_id', $id)->pluck('id')->toArray();
                if(!empty($merchant_manager)){
                    foreach ($merchant_manager as $m_id){
                        forget('merchant_auths_' . $m_id);
                    }
                }
                unset($merchant_manager, $m_id);
                $result = [
                    'ret'  => 0,
                    'msg'  => '操作成功',
                ];
            } else {
                $result = [
                    'ret'  => 300,
                    'msg'  => '删除失败',
                ];
            }
        } while (FALSE);
        json($result);
    }
}
